What is the difference between Java and | | and |

  • 2020-06-19 10:14:53
  • OfStack

1. When the variables on both sides of the operator are boolean variables

First list the code:


public class Test {
  public static void main(String[] args) {
    boolean a = false;
    boolean b = true;
    if (a && b) {
      // do something
      System.out.println("a&&b");
    }
    if (a & b) {
      // do something
      System.out.println("a&b");
    }
  }
}

Although both if statements print the result the same!! (No output)

But the actual execution process is not the same (you can try debug debugging)

& & The logical operation and is true only when both conditions are true.

So || logical operation or is true as long as there is 1 condition that is true.

while & And | are bits.

The biggest difference between logical and bitwise operations is that

Logic operation supports short circuit operation,

The bit operation does not support short circuit operation.

The short circuit operation is the bit operation if (condition 1 & Condition 2) {}

If the first condition is not satisfied, then the second condition is also judged,

But the logical operation if(condition 1 & & 2) {}

We don't judge condition 2 when condition 1 is not met.

The logical || is the same as the bit operation |.

2. When the variables on both sides of the operator are of type int

a only & The bitwise and operation of b or a|b performs bitwise or operation. Just calculate it normally


Related articles: